package com.htstar.ovms.enterprise.handle.listener;


import com.alibaba.excel.ExcelWriter;
import com.htstar.ovms.common.core.constant.SecurityConstants;
import com.htstar.ovms.common.excel.util.ExcelHandler;
import com.htstar.ovms.common.minio.service.MinioTemplate;
import com.htstar.ovms.device.api.entity.ExportRecord;
import com.htstar.ovms.device.api.feign.ExportRecoreFeign;
import com.htstar.ovms.enterprise.api.req.CarItemPageReq;
import com.htstar.ovms.enterprise.api.vo.CarFuelExcelVO;
import com.htstar.ovms.enterprise.api.vo.CarOtherExcelVO;
import com.htstar.ovms.enterprise.handle.event.CarFuelExcelExportEvent;
import com.htstar.ovms.enterprise.handle.event.CarOtherExcelExportEvent;
import com.htstar.ovms.enterprise.service.CarFuelItemService;
import com.htstar.ovms.enterprise.service.CarOtherItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class CarOtherExcelExportListener implements ApplicationListener<CarOtherExcelExportEvent> {
    @Autowired
    private CarOtherItemService carOtherItemService;

    @Autowired
    MinioTemplate minioTemplate;

    @Autowired
    private ExportRecoreFeign exportRecoreFeign;

    @Value("${excel.queryLimit}")
    private int queryLimit;

    @Override
    @Async
    public void onApplicationEvent(CarOtherExcelExportEvent carOtherExcelExportEvent) {
        CarItemPageReq exportReq = carOtherExcelExportEvent.getExportReq();

        ExportRecord exportRecord = new ExportRecord();
        exportRecord.setId(exportReq.getExportId());//更新导出表的实体
        Integer alarmCount = carOtherItemService.getExportCount(exportReq);
        int numSheet = 1;//所需要的sheet数量，初始1
        int sheetLimit = 500;
//        int queryLimit = 100; //改为从配置文件读取
        if (alarmCount > sheetLimit) {
            numSheet = alarmCount / sheetLimit + 1;
        }
        int alarmCountPage = 1; //分页查询：每次5000
        if (alarmCount > queryLimit) {
            alarmCountPage = (alarmCount / queryLimit) + 1;
        }

        int count = 0;
        int num = 0;
        ExcelHandler handler = null;
        ExcelWriter excelWriter = null;
        String url = null;
        try {
            //创建handler对象--参数:文件夹名
            handler = new ExcelHandler("AlarmExcel/" + exportReq.getUserId());
            excelWriter = handler.create(exportReq.getFileName(), CarOtherExcelVO.class, numSheet);

            List<CarOtherExcelVO> list = new ArrayList<>(1024);
            for (int t = 1; t <= alarmCountPage; t++) {//模拟分页页数 每页50W数据
                exportReq.setCurrent(t);
                exportReq.setSize(queryLimit);
                list = carOtherItemService.queryPageForExcel(exportReq);
                //count 将控制插入哪一个sheet
                count += list.size();
                handler.write(excelWriter, list, count);
                list.clear();//必须clear,否则数据会重复
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            exportRecord.setExportStatus(3);
            exportRecoreFeign.updateById(exportRecord, SecurityConstants.FROM_IN);
            log.error("报表导出错误");
            return;
        } finally {
            if (null != excelWriter) {
                handler.finish(excelWriter);
            }
        }
        //上传文件
        String location = "AlarmExcel/" + exportReq.getUserId() + "/" + exportReq.getFileName() + ".xlsx";
        String saveAsFileName = exportReq.getFileName() + ".xlsx";
        String bucketName = "excel";
        try {
            url = uploadExcel(location, saveAsFileName, bucketName);
        } catch (Exception e) {
            exportRecord.setExportStatus(3);
            exportRecoreFeign.updateById(exportRecord, SecurityConstants.FROM_IN);
            log.error("报表上传错误");
            return;
        }
        //更新状态
        exportRecord.setExportStatus(2);
        exportRecord.setExportUrl(String.format("/admin/sys-file/%s/%s", bucketName, saveAsFileName));
        exportRecoreFeign.updateById(exportRecord, SecurityConstants.FROM_IN);
        File file = new File(location);
        file.delete();
    }


    public String uploadExcel(String location, String saveAsFileName, String bucketName) throws Exception {
        minioTemplate.createBucket(bucketName);
        FileInputStream fileInputStream = null;
        Map<String, String> resultMap;
        try {
            fileInputStream = new FileInputStream(new File(location));
//        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
//        String fileName = "安防警报_1_2021-01-13_09-40-41.xlsx";
            resultMap = new HashMap<>(4);
//		resultMap.put("bucketName", CommonConstants.BUCKET_NAME);
            resultMap.put("bucketName", bucketName);
            resultMap.put("fileName", saveAsFileName);
            resultMap.put("url", String.format("/admin/sys-file/%s/%s", bucketName, saveAsFileName));
            minioTemplate.putObject(bucketName, saveAsFileName, fileInputStream);
        } finally {
            fileInputStream.close();
        }
        //文件管理数据记录,收集管理追踪文件
//            fileLog(file, fileName);
        return resultMap.get("url");
    }
}
